<template>
  <div class="app-container home">
    <!-- 搜索区域 -->
    <el-form :model="searchForm" class="search-form">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="知识点名称">
            <el-input
              v-model="searchForm.name"
              placeholder="请输入知识点名称"
            />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="年级">
            <el-select
              v-model="searchForm.grades"
              placeholder="请选择年级"
              style="width: 100%"
            >
              <el-option
                v-for="grade in gradeOptions"
                :key="grade.id"
                :label="grade.name"
                :value="grade.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
<!-- 
        <el-col :span="6">
       
         <el-select v-model="searchForm.version" placeholder="请选择版本" style="width: 100%">
          <el-option label="数学" value="1" />
          <el-option label="英语" value="2" />
        </el-select>
  
        </el-col> -->

        <el-col :span="4">
          <el-form-item label="科目">
            <el-select
              v-model="searchForm.subject"
              placeholder="请选择科目"
              style="width: 100%"
            >
              <el-option
                v-for="subject in subjectOptions"
                :key="subject.id"
                :label="subject.name"
                :value="subject.id"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <!-- 操作栏 -->
          <div class="operation-bar">
            <el-button type="primary" @click="handleAdd">新增知识点</el-button>
            <div class="search-actions">
              <el-button type="primary" @click="handleSearch">搜索</el-button>
              <el-button @click="handleReset">重置</el-button>
            </div>
          </div>
        </el-col>
      </el-row>
    </el-form>

    <!-- 表格区域 -->
    <el-table
      ref="tableRef"
      :data="tableData"
      border
      stripe
      :row-key="(row) => row.id"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <!-- 修改知识点名称列为链接样式 -->
      <el-table-column label="知识点名称" min-width="180">
        <template #default="scope">
          <el-link type="primary" @click="handleDetail(scope.row)">
            {{ scope.row.name }}
          </el-link>
        </template>
      </el-table-column>
      <!-- 原有其他列保持不变 -->
      <el-table-column prop="grades" label="年级" min-width="150">
        <template #default="scope">
          <el-tag v-for="grade in scope.row.grades" :key="grade">{{
            grade
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="subject" label="科目" width="100" />
      <el-table-column prop="version" label="版本" width="120" />
      <el-table-column label="操作" width="160">
        <template #default="scope">
          <el-button type="text" size="small" @click="handleEdit(scope.row)"
            >编辑</el-button
          >
          <el-button
            type="text"
            size="small"
            @click="handleDelete(scope.row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <el-pagination
      class="pagination"
      :current-page="currentPage"
      :page-size="pageSize"
      :total="total"
      @current-change="handlePageChange"
      @size-change="handleSizeChange"
      layout="prev, pager, next, jumper"
    />

    <!-- 新增批量操作栏 -->
    <div v-if="selectedRows.length > 0" class="batch-actions">
      <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
      <el-button @click="handleCancelSelection">取消勾选</el-button>
    </div>
  </div>
</template>

<script setup>
import { useRouter } from "vue-router";
import { reactive, ref, onMounted } from "vue";
import { ElMessage, ElMessageBox, ElLoading } from "element-plus";
import * as knowledgesApi from "@/api/knowledges.js";


// 搜索表单
const searchForm = reactive({
  name: "",
  grades: '',
  // version: '1',
  subject: "",
});

// 年级选项
const gradeOptions = ref(knowledgesApi.grades);

const subjectOptions = ref(knowledgesApi.subjects);


// 地区选项（固定安徽-合肥）
const versionOptions = ref([
  {
    value: "安徽",
    label: "安徽",
    children: [
      {
        value: "合肥",
        label: "合肥",
      },
    ],
  },
]);

// 表格数据
const tableData = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const selectedRows = ref([]);
const tableRef = ref(null);
const router = useRouter();

// 搜索方法
const handleSearch = async () => {
  try {

    // 准备请求参数
    const requestParams = {
      name: searchForm.name,
      subjectId: searchForm.subject,
      gradeId: searchForm.grades || undefined

    };
    
    // 调用API获取数据
    const response = await knowledgesApi.pageQueryKnowledgePoint(
      requestParams,
      currentPage.value,
      pageSize.value
    );
    
    // 处理返回数据
    if (response.code === 200 && response.rows) {
      // 假设API返回的数据格式需要转换以适应表格
      tableData.value = response.rows || [];
      total.value = response.rows || 0;
    } else {
      ElMessage.error('获取知识点列表失败');
      tableData.value = [];
      total.value = 0;
    }
  } catch (error) {
    ElMessage.error('获取知识点列表异常：' + error.message);
  } finally {
    // 关闭加载动画
    ElLoading.service().close();
  }
};

// 重置方法
const handleReset = () => {
  searchForm.name = "";
  searchForm.grades = [];
  searchForm.version = '1';
  searchForm.subject = "";
  currentPage.value = 1;
  handleSearch();
};

// 分页变化
const handlePageChange = (page) => {
  currentPage.value = page;
  handleSearch();
};

const handleSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1;
  handleSearch();
};

// 多选变化
const handleSelectionChange = (val) => {
  selectedRows.value = val;
};

// 编辑操作
const handleEdit = (row) => {
  router.push({
    path: "/knowledges/edit",
    query: { id: row.id },
  });
};

const handleDetail = (row) => {
  router.push({
    path: "/knowledges/edit",
    query: { id: row.id, isDetail: true },
  });
};

// 单条删除
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm("确定删除该知识点？", "提示", {
      type: "warning",
    });
    
    const response = await knowledgesApi.delKnowledgePoint([id]);
    
    if (response.code === 200) {
      ElMessage.success("删除成功");
      handleSearch(); // 删除后重新加载数据
    } else {
      ElMessage.error(response.msg || '删除失败');
    }
  } catch (error) {
    // 用户取消确认也会进入这里，不需要处理
    if (error !== 'cancel') {
      ElMessage.error('删除操作异常：' + error.message);
    }
  }
};

// 批量删除
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请选择需要删除的知识点");
    return;
  }
  
  try {
    await ElMessageBox.confirm("确定删除选中的知识点？", "提示", {
      type: "warning",
    });
    
    const ids = selectedRows.value.map((row) => row.id);
    const response = await knowledgesApi.delKnowledgePoint(ids);
    
    if (response.code === 200) {
      ElMessage.success("批量删除成功");
      handleCancelSelection(); // 清空选择
      handleSearch(); // 重新加载数据
    } else {
      ElMessage.error(response.msg || '批量删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除操作异常：' + error.message);
    }
  }
};

// 新增知识点
const handleAdd = () => {
  router.push({ path: "/knowledges/edit", query: { isAdd: true } });
};

// 取消勾选方法
const handleCancelSelection = () => {
  selectedRows.value = [];
  if (tableRef.value) {
    tableRef.value.clearSelection();
  }
};

// 初始化加载数据
onMounted(() => {
  handleSearch();
});
</script>

<style scoped lang="scss">
.operation-bar {
  display: flex;
  justify-content: space-between;
}

.search-form {
  margin-bottom: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 4px;

  .search-actions {
    display: flex;
    gap: 8px;
    padding-top: 24px;
  }
}

.pagination {
  margin-top: 20px;
  padding: 0 16px;
  display: flex;
  justify-content: flex-end;
}

.batch-actions {
  margin: 16px 0;
  padding: 0 16px;
  display: flex;
  gap: 16px;
  justify-content: flex-end; // 右对齐
}

.el-table .el-tag {
  margin-right: 4px;
}
</style>
